package com.jming.jike.filter;

import com.alibaba.fastjson.JSON;
import com.jming.jike.common.BusinessException;
import com.jming.jike.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 检查用户是否已经完成登录
 *
 * @author jming
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    /**
     * 路径匹配器，支持通配符
     */
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Value("${filter.isOperFilter}")
    private Boolean isOperFilter;

    @Value("${filter.notFilters}")
    private String[] notFilters;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 解决响应乱码
        response.setContentType("text/html;charset=UTF-8");

        try {

            // 如果关闭过滤 则直接放行所有
            if (!isOperFilter) {
                filterChain.doFilter(request, response);
                return;
            }

            //1、获取本次请求的URI /backend/index.html
            String requestUrl = request.getRequestURI();

            log.info("拦截到请求:{}", requestUrl);

            // 2、判断本次请求是否需要处理
            boolean check = check(notFilters, requestUrl);

            // 3、如果开启过滤 则放行不需要处理的Url
            if (isOperFilter && check) {
                log.info("本次请求{}不需要处理", requestUrl);
                filterChain.doFilter(request, response);
                return;
            }

            // 4、判断登录状态，如果已登录，则直接放行
            if (request.getSession().getAttribute("Employee") != null || request.getSession().getAttribute("User") != null) {

                filterChain.doFilter(request, response);
                return;
            }

            log.info("用户未登录");
            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
            response.getWriter().write(JSON.toJSONString(new ResponseResult<>("404", "NOT LOGIN")));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("500");
        }
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param requestUrl
     * @return
     */
    public boolean check(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
